import { useEffect, useRef } from 'react';

interface IUseInterval {
  go: () => void;
  cancel: () => void;
}

let timer;
const useInterval = (
  callback: () => void,
  delay: number | null | undefined,
  options?: {
    immediate?: boolean;
  }
): IUseInterval => {
  const immediate = options.immediate; // 是否在首次渲染时立即执行

  const saveCallback = useRef<any>();

  // remember the last callback
  useEffect(() => {
    saveCallback.current = callback;
  });

  function tick() {
    saveCallback?.current();
  }

  // set up the interval
  useEffect(() => {
    if (delay === undefined || delay === null) return;

    if (immediate) {
      saveCallback.current();
    }

    if (delay !== null) {
      timer = setInterval(tick, delay);

      return () => {
        clearInterval(timer);
      };
    }
  }, [delay, immediate]);

  return {
    go: () => {
      timer = setInterval(tick, delay);
    },
    cancel: () => {
      clearInterval(timer);
      timer = null;
    },
  };
};

export default useInterval;
export { IUseInterval };

// const [count, setCount] = useState(0);
// const interval = useInterval(() => {
//   setCount(count + 1);
// }, 1000, {immediate: true});
